package com.alipay.rebate.shop.helper;

import com.alipay.rebate.shop.constants.UserIncomeConstant;
import com.alipay.rebate.shop.dao.mapper.OrdersMapper;
import com.alipay.rebate.shop.dao.mapper.PunishOrdersMapper;
import com.alipay.rebate.shop.dao.mapper.UserIncomeMapper;
import com.alipay.rebate.shop.dao.mapper.UserMapper;
import com.alipay.rebate.shop.model.Orders;
import com.alipay.rebate.shop.model.PunishOrders;
import com.alipay.rebate.shop.model.UserIncome;
import com.alipay.rebate.shop.pojo.user.admin.PunishWorkOrder;
import com.alipay.rebate.shop.pojo.user.admin.PunishWorkOrderReq;
import com.alipay.rebate.shop.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component
public class PunishWorkOrderHelper {

    @Resource
    OrdersMapper ordersMapper;
    @Resource
    UserIncomeMapper userIncomeMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    PunishOrdersMapper punishOrdersMapper;

    private Logger logger = LoggerFactory.getLogger(PunishWorkOrderHelper.class);

    public void handlePunishWorkOrder(PunishWorkOrderReq req){
        List<PunishWorkOrder> workOrder = req.getWorkOrder();
        logger.debug("workOrder is : {}",workOrder);
        for (PunishWorkOrder punishWorkOrder : workOrder){
            String punishTradeId = punishWorkOrder.getTradeId();
            String tradeId = punishTradeId.substring(punishTradeId.indexOf(':') + 1);

            PunishOrders punishOrdersByTradeId = punishOrdersMapper.getPunishOrdersByTradeId(tradeId);
            // 记录存在
            if (punishOrdersByTradeId != null){
                logger.debug("punishOrdersByTradeId has");
                // 记录存在，该订单已处理过
                continue;
            }
            punishWorkOrder.setTradeId(tradeId);
            // 获取订单信息
            Orders orders = ordersMapper.selectOrdersByTradeId(punishWorkOrder.getTradeId());
            if (orders != null) {
                if (orders.getIsRecord() == 0){
                    // 订单没有奖励过用户，不需要扣款直接保存
                    PunishOrders punishOrders = buildPunishOrders(punishWorkOrder);
                    punishOrdersMapper.insertSelective(punishOrders);
                    continue;
                }
                // 修改订单,标识订单为违规订单
                orders.setCustomStatus(1L);
                ordersMapper.updateByPrimaryKeySelective(orders);
                logger.debug("orders.getPubSharePreFee() and punishWorkOrder.getPunishMoney() is : {},{}", orders.getPubSharePreFee(), punishWorkOrder.getPunishMoney());
                // 计算扣款比例
                BigDecimal scale = calculationChargebackScale(orders.getPubSharePreFee(), punishWorkOrder.getPunishMoney());
                // 计算应该减去用户多少集分宝
                logger.debug("orders.getUserCommission() and scale is : {},{}",orders.getUserCommission(),scale);
                BigDecimal money = orders.getUserCommission().multiply(scale);
                long uit = money.multiply(new BigDecimal("100")).longValue();
                logger.debug("scale and money dan uit is : {}.{},{}", scale, money, uit);

                if (orders.getUserId() != null || orders.getPromoterId() != null) {
                    if (orders.getUserId() != null) {
                        userMapper.plusUserUit(-uit, orders.getUserId());
                    }
                    if (orders.getPromoterId() != null){
                        userMapper.plusUserUit(-uit, orders.getPromoterId());
                    }
                    UserIncome userIncome = buildUserIncome(orders, money);
                    // 插入扣款记录
                    userIncomeMapper.insertSelective(userIncome);
                }

                // 处理过的工单保存到数据库
                PunishOrders punishOrders = buildPunishOrders(punishWorkOrder);
                punishOrdersMapper.insertSelective(punishOrders);
            }
        }
    }

    private BigDecimal calculationChargebackScale(BigDecimal pubSharePreFee,BigDecimal punishMoney){
        BigDecimal scale = punishMoney.divide(pubSharePreFee,2,BigDecimal.ROUND_HALF_DOWN);
        return scale;
    }


    private UserIncome buildUserIncome(Orders orders,BigDecimal money){
        UserIncome nUserIncome = new UserIncome();
        if (orders.getUserId() != null) {
            nUserIncome.setUserId(orders.getUserId());
        }else{
            nUserIncome.setUserId(orders.getPromoterId());
        }
        nUserIncome.setParentTradeId(orders.getTradeParentId());
        nUserIncome.setAwardType(UserIncomeConstant.UIT_AWARD_TYPE);

        nUserIncome.setCreateTime(DateUtil.getNowStr());
        nUserIncome.setUpdateTime(DateUtil.getNowStr());
        nUserIncome.setSpecialId(orders.getSpecialId());
        nUserIncome.setRelationId(orders.getRelationId());
        nUserIncome.setType(UserIncomeConstant.PUNISH_WORK_ORDER_TYPE);
        nUserIncome.setMoney(money);
        nUserIncome.setStatus(UserIncomeConstant.IS_PAID);
        nUserIncome.setTkStatus(orders.getTkStatus());
        nUserIncome.setTradeId(orders.getTradeId());
        return nUserIncome;
    }

    private PunishOrders buildPunishOrders(PunishWorkOrder workOrder){
        PunishOrders punishOrders = new PunishOrders();
        punishOrders.setPunishMoney(workOrder.getPunishMoney());
        punishOrders.setTradeId(workOrder.getTradeId());
        punishOrders.setType(workOrder.getType());
        punishOrders.setWorkOrderId(workOrder.getWorkOrderId());
        return punishOrders;
    }

}
